#include "printthread.h"

PrintThread::PrintThread(QPrinter &pr, Poppler::Document *doc, DocumentNotes &dn) :
		QThread(), _printer(pr), _doc(doc), _notes(dn) {
	_from=0;
	_to=0;
}

void PrintThread::run() {
	_printer.setFullPage(true);
	QPainter painter;
	painter.begin(&_printer);
	int from= _from ? _from-1 : 0;
	int to= _to ? _to : _doc->numPages();
	double currentScale=1.0;//_printer.resolution()/72.0;
	QList<ClickPoint> clickPoints;

	QSettings settings;
	QFont font = settings.value("textFont", painter.font()).value<QFont>();
	bool ok;
	font.setPointSize(settings.value("fontSize", 9).toInt(&ok));
	if (ok) painter.setFont(font);
    painter.setPen(settings.value("rectColor").value<QColor>());
    QColor color=settings.value("clickPointColor").value<QColor>();
	bool icon=settings.value("noteIcon", true).toBool();

	for (int p=from; p<to; p++) {
		QImage image = _doc->page(p)->renderToImage(_printer.resolution(), _printer.resolution());
		painter.drawImage(QPoint(0, 0), image);

		PageNotes *notes=_notes.getNotesForPage(p);
		clickPoints.clear();

		    if (!notes->textNotes().isEmpty()) {
		    	QList<TextNote> &textNotes=notes->textNotes();
		    	for (int i=0; i<textNotes.count(); i++) {
		    		clickPoints.append(ClickPoint(&textNotes[i]));
		    	}
		    }

		    if (!notes->rectNotes().isEmpty()) {
		    	QList<RectNote> &rectNotes=notes->rectNotes();
		    	for (int i=0; i<rectNotes.count(); i++) {
		    		RectNote *note=&rectNotes[i];
		    		if (!note->valid()) continue;
		    		if (!note->text().isEmpty()) clickPoints.append(ClickPoint(note));
		    		painter.drawRect(QRectF(note->rectangle().topLeft()*currentScale, note->rectangle().size()*currentScale));
		    	}
		    }
		    painter.setPen(settings.value("textColor").value<QColor>());
		    if (!clickPoints.isEmpty()) {
		    	for (int i=0; i<clickPoints.count(); i++) {
		    		ClickPoint point=clickPoints.at(i);
		    		if (!point.note()->valid()) continue;

		    		if (icon)
		    			painter.drawImage(point.point()*currentScale, image);
		    		else
		    			painter.fillRect(QRectF(point.point()*currentScale, QSize(11, 11)), color);

		    		if (!point.note()->drawRect().isEmpty()) {
		    			QRectF drawRect(point.note()->drawRect().topLeft()*currentScale, point.note()->drawRect().size()*currentScale);
		    			painter.drawText(drawRect, point.note()->text());
		    		}
		    	}
		    }

		if (p<to-1) _printer.newPage();
	}
	painter.end();

}
